<?php

namespace app\admin\controller\tuiguang;
include_once("/www/wwwroot/immortal-knight/vendor/phpqrcode/phpqrcode.php");
use app\common\controller\Backend;
// use app\admin\library\phpq;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use Kkokk\Poster\PosterManager;
use Kkokk\Poster\Exception\Exception;
/**
 * 安装包下载管理
 *
 * @icon fa fa-circle-o
 */
class AppInfo extends Backend
{
    
    /**
     * AppInfo模型对象
     * @var \app\admin\model\tuiguang\AppInfo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\tuiguang\AppInfo;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list   = $list->toArray();
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
//                    dd($params);
                    $result = $this->model->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
                        $pk       = $row->getPk();
                        if (!isset($params[$pk])) {
                            $params[$pk] = $row->$pk;
                        }
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $result = $row->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('row', $row);

        return $this->view->fetch();
    }

    public function tuiguang($ids = null)
    {
        $row = $this->model->get($ids);
        // dd($row);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // dd($row->app_url);
//        dd();
        if(empty($row->dowload_url)){
            $id=Session::get('admin.id');
            $android_src='tuiguang/game/chuanqi_android'.$row->a_id.'.png';
            $url='http://47.96.128.147/index/dowload/index?app_id='.$ids;
            $android=$this->getActivityImg('/www/wwwroot/immortal-knight/public'.$row->background,$url,200,610,170,1,$android_src,$row->a_id);
           $row->qrcode='/'.$android;
           $row->dowload_url=$url;
           $row->save();
           $app = $this->model->get($ids);
           $android_qrcode=$app->qrcode;
        }else{
            $android_qrcode=$row->qrcode;
        }


        
        $this->view->assign('android_img', $android_qrcode);
        $this->view->assign('ios_img', 0);
        return $this->view->fetch();
    }
    
    /**
     * 在背景图上生成二维码
     * $bg_img    背景图地址
     * $url       二维码内容url
     * $x   二维码在背景图片上位置的左边距,单位：px （例：436）
     * $y   二维码在背景图片上位置的上边距,单位：px （例：1009）
     * $qrcode_size  二维码（正方形）的尺寸,单位：px （例：238）
     * $white_edge   二维码白边大小
     * $echo_path   生成的二维码海报图片存放路径
     **/
    public function getActivityImg($bg_img, $url, $x=0, $y=0, $qrcode_size, $white_edge=0, $echo_path,$a_id){
    // 	include_once("/library/phpqrcode/phpqrcode.php");  //放到你的代码文件头部去
        $errorCorrectionLevel = QR_ECLEVEL_L;          //容错级别
        $matrixPointSize = 2;                           //生成二维码图片大小
        $qrcode = "qrcod".$a_id.".png";							//用来存放二维码的变量，不是实际图片

        //生成二维码图片
        //参数内容:二维码储存内容，生成存储，防错等级，二维码大小，白边大小
        // vendor("phpqrcode.phpqrcode");
        $QRcode = new \QRcode();
        $QRcode->png($url, $qrcode, $errorCorrectionLevel, $matrixPointSize, $white_edge);
        // QRcode::png($url, $qrcode, $errorCorrectionLevel, $matrixPointSize, $white_edge);	//我这个白边大小是0，因为加上白边控制不了大小，不能完美契合背景图（白边可以让设计搞^.^）
        
        //合并背景图和二维码
        $background = imagecreatefromstring(file_get_contents($bg_img));	//资源
        $qrcode_res = imagecreatefromstring(file_get_contents($qrcode));	//资源
        // echo file_get_contents($qrcode);die;
        list($src_w, $src_h) = getimagesize($qrcode);
		//参数内容:目标图象连接资源，源图象连接资源，目标X坐标点，目标Y坐标点，源的X坐标点，源的Y坐标点，目标宽度，目标高度，源图象的宽度，源图象的高度（参数有疑问的话到：https://www.php.net/manual/zh/function.imagecopyresampled.php 去看，其他博客里瞎写）
        imagecopyresampled($background, $qrcode_res, $x, $y, 0, 0, $qrcode_size, $qrcode_size, $src_w, $src_h);

         //输出到本地文件夹，返回生成图片的路径
        if(!is_dir(dirname($echo_path))){
            mkdir(dirname($echo_path), 0755, true);
            chown(dirname($echo_path), 'nobody');
            chgrp(dirname($echo_path), 'nobody');
        }

        imagepng($background,$echo_path);	//把生成的背景图+二维码资源 放到了目标路径下
        imagedestroy($background);
        imagedestroy($qrcode_res);
        
        return $echo_path;
    }
    
}
